﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace MemoDb
{
    public class CollectionBuilder
    {
        private readonly ArrayList items = new ArrayList();

        public void Add(object item)
        {
            items.Add(item);
        }

        public object BuildFor(Type collectionType)
        {
            if (collectionType.IsArray)
                return items.ToArray(collectionType.GetElementType());

            Type type;

            if (IsGenericListInterface(collectionType))
                type = typeof (List<>).MakeGenericType(collectionType.GetGenericArguments());
            else if (collectionType.IsInterface)
                type = typeof (ArrayList);
            else if (collectionType.HasParameterlessConstructor())
                type = collectionType;
            else
                throw new InvalidOperationException(string.Format("Collection type {0} is not supported.",
                                                                  collectionType.FullName));
            
            var list = (IList)Activator.CreateInstance(type);

            foreach (var item in items)
                list.Add(item);

            return list;
        }

        private static bool IsGenericListInterface(Type collectionType)
        {
            return collectionType.IsInterface && collectionType.IsGenericType &&
                   collectionType.GetGenericArguments().Length == 1;
        }
     }
}